<template>
  <div style="width: 100%; height: 100%;" class="login-background">
    <el-row class="margin-top-log" :gutter="100">
      <el-col :span="6" :offset="9">
        <el-card shadow="always">
          <el-row>
            <div v-if="buttonStatus === 1" style="text-align: center">
              <label for="fileInput">
                <el-avatar size="large" :src="this.$global.mediaHost + this.avatarUrl"></el-avatar>
              </label>
              <input v-show="false" type="file" id="fileInput" accept="image/*" @change="uploadImage">
            </div>
          </el-row>
          <el-row v-show="buttonStatus===1" style="text-align: center">
            用户名：{{ this.userName }}
          </el-row>
          <el-row v-if="buttonStatus===1 && updateNickNameFlag === false" style="text-align: center">
            昵称：{{ this.nickName }}&nbsp;&nbsp;<i style="color: #3a8ee6" class="el-icon-edit"
                                                 @click="updateNickNameFlag=true"></i>
          </el-row>

          <el-row v-if="buttonStatus===1 && updateNickNameFlag === true">
            <el-input placeholder="请输入昵称" v-model="nickName" class="input-with-select">
              <el-button slot="append" icon="el-icon-edit" @click="updateNickName"></el-button>
            </el-input>
          </el-row>

          <el-row v-show="buttonStatus===2">
            <el-input placeholder="请输入旧密码" v-model="oldPwd" show-password></el-input>
          </el-row>
          <el-row v-show="buttonStatus===2">
            <el-input placeholder="请输入新密码" v-model="pwd" show-password></el-input>
          </el-row>
          <el-row v-show="buttonStatus===2">
            <el-input placeholder="请确认新密码" v-model="confirmPwd" show-password></el-input>
          </el-row>
          <el-row class="text-center">
            <el-button type="primary" size="mini" @click="buttonStatus === 1 ? toHomePage() : updatePwd()">
              {{ buttonStatus === 1 ? '返回主页' : '确认修改' }}
            </el-button>
          </el-row>
          <el-row class="text-center">
            <el-link type="primary" :underline="false" @click="changeStatus()">
              {{ buttonStatus === 1 ? '修改密码' : '个人信息' }}
            </el-link>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      userName: this.$global.getUser().userName,
      oldPwd: '',
      pwd: '',
      confirmPwd: '',
      nickName: this.$global.getUser().nickName,
      avatarId: 1,
      paramsData: {},
      buttonStatus: 1,
      avatarUrl: this.$global.getUser().avatarUrl,
      updateNickNameFlag: false
    }
  },
  methods: {
    uploadImage: function (e) {
      console.log(e.target.files[0])
      if (e.target.files[0] !== undefined) {
        let fileName = e.target.files[0].name;
        let fileType = e.target.files[0].type;
        let imageType = this.$global.imageType
        if (!fileType.includes(imageType)) {
          this.$message.error({
            message: "文件类型错误",
            center: true,
            duration: 1000
          });
          return false;
        }
        fileName = "/" + imageType + "/" + this.$global.randomStr(24) + fileName.substring(fileName.lastIndexOf("."))
        const OSS = require('ali-oss')
        const client = new OSS({
          bucket: this.$global.bucket,
          region: this.$global.region,
          secure: true,
          accessKeyId: this.$global.accessKeyId,
          accessKeySecret: this.$global.accessKeySecret,
        });
        const asyncThis = this

        async function put() {
          try {
            let loading = asyncThis.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading'
            });
            //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
            let result = await client.put(fileName, e.target.files[0]);
            console.log(result);
            loading.close();
            asyncThis.avatarUrl = fileName;
            //修改头像
            asyncThis.updateAvatarUrl()
          } catch (e) {
            console.log(e);
          }
        }

        put();
      }
    },
    updateNickName: function () {
      if (this.checkNickNameInput()) {
        this.updateNickNameFlag = false
        this.paramsData.nickName = this.nickName
        this.$ajax({
          method: 'post',
          headers: this.$global.headers,
          url: this.$global.host + '/v1/user/updateNickName',
          data: JSON.stringify({
            "data": this.paramsData,
            "user": this.$global.getUser(),
            "teamId": this.$global.getTeamId()
          }),
        }).then(response => {
          const responseData = response.data.data;
          const responseState = response.data.state
          if (2000 === responseState.code) {
            this.$message.success({
              message: '修改用户昵称成功',
              center: true,
              duration: 1000
            });
            this.$global.setUser(responseData.user)
          } else {
            this.$message.error({
              message: responseState.msg,
              center: true,
              duration: 1000
            });
          }
        }).catch(function (err) {
          console.log(err)
        })
      }
    },
    updateAvatarUrl: function () {
      this.paramsData.avatarUrl = this.avatarUrl
      this.$ajax({
        method: 'post',
        headers: this.$global.headers,
        url: this.$global.host + '/v1/user/updateAvatarUrl',
        data: JSON.stringify({
          "data": this.paramsData,
          "user": this.$global.getUser(),
          "teamId": this.$global.getTeamId()
        }),
      }).then(response => {
        const responseData = response.data.data;
        const responseState = response.data.state
        if (2000 === responseState.code) {
          this.$message.success({
            message: '修改用户头像成功',
            center: true,
            duration: 1000
          });
          this.$global.setUser(responseData.user)
        } else {
          this.$message.error({
            message: responseState.msg,
            center: true,
            duration: 1000
          });
        }
      }).catch(function (err) {
        console.log(err)
      })
    },
    updatePwd: function () {
      if (this.checkPwdInput()) {
        this.paramsData.oldPwd = this.oldPwd
        this.paramsData.pwd = this.pwd
        this.paramsData.confirmPwd = this.confirmPwd
        this.$ajax({
          method: 'post',
          headers: this.$global.headers,
          url: this.$global.host + '/v1/user/updatePwd',
          data: JSON.stringify({
            "data": this.paramsData,
            "user": this.$global.getUser(),
            "teamId": this.$global.getTeamId()
          }),
        }).then(response => {
          const responseData = response.data.data;
          const responseState = response.data.state
          if (2000 === responseState.code) {
            this.$message.success({
              message: '修改密码成功，请重新登录',
              center: true,
              duration: 1000
            });
            this.$global.removeTeamId()
            this.$global.removeUser()
            this.$router.push({path: "/login"})
          } else {
            this.$message.error({
              message: responseState.msg,
              center: true,
              duration: 1000
            });
          }
        }).catch(function (err) {
          console.log(err)
        })
      }
    },
    toHomePage:function () {
      this.$router.push({path: "/homePage"})
    },
    /**
     * 改变按钮状态
     */
    changeStatus: function () {
      if (this.buttonStatus === 1) {
        this.buttonStatus = 2
      } else {
        this.buttonStatus = 1
      }
      this.nickName = this.$global.getUser().nickName
      this.avatarUrl = this.$global.getUser().avatarUrl
      this.userName = this.$global.getUser().userName
      this.updateNickNameFlag = false
      this.oldPwd = ''
      this.pwd = ''
      this.confirmPwd = ''
    },
    checkNickNameInput: function () {
      if (!this.$global.checkSpecificKey(this.nickName)) {
        this.$message.warning({
          message: '不允许输入特殊符号',
          center: true,
          duration: 1000
        });
        return false
      }
      if (this.nickName.length < 1 || this.nickName.length > 10) {
        this.$message.warning({
          message: '昵称必须输入1~20位字符',
          center: true,
          duration: 1000
        });
        return false;
      }
      return true;
    },
    checkPwdInput: function () {
      if (!this.$global.checkSpecificKey(this.oldPwd + this.pwd + this.confirmPwd)) {
        this.$message.warning({
          message: '不允许输入特殊符号',
          center: true,
          duration: 1000
        });
        return false
      }
      if (this.oldPwd.length < 6 || this.oldPwd.length > 20) {
        this.$message.warning({
          message: '密码必须输入6~20位字符',
          center: true,
          duration: 1000
        });
        return false;
      }
      if (this.pwd.length < 6 || this.pwd.length > 20) {
        this.$message.warning({
          message: '密码必须输入6~20位字符',
          center: true,
          duration: 1000
        });
        return false;
      }
      if (this.confirmPwd.length < 6 || this.confirmPwd.length > 20 || this.pwd !== this.confirmPwd) {
        this.$message.warning({
          message: '两次输入的密码不一致',
          center: true,
          duration: 1000
        });
        return false;
      }
      return true;
    }
  }
}
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.text-center {
  text-align: center;
}

.margin-top-log {
  margin-top: 200px;
}

.login-background {
  position: fixed;
  top: 0;
  left: 0;
  /*以上三句是让整个span放在屏幕的最左上方*/
  height: 100%;
  width: 100%;
  /*以上两句实现全屏大小*/
  background: url("https://media.maixy.top/wode/b1.jpg") no-repeat center 0; /*引入背景图，不重复出现*/
  background-size: cover; /*图片随屏幕大小同步缩放,但是图片画面可能只显示一部分*/
}
</style>
